const { NodeSSH } = require("node-ssh");
const fs = require('fs');
const ora = require("ora");
const chalk = require("chalk");
const errorLog = (error) => console.log(chalk.red(`---------------> ${error}`));
const defaultLog = (log) => console.log(chalk.blue(`---------------> ${log}`));
const successLog = (log) => console.log(chalk.green(`---------------> ${log}`));
// var path_ ='E:/web/node/lowcode/v3_node/dist/dist11.zip'

module.exports = (path) => {
  // 目标文件路径 path
  const ssh = new NodeSSH();
  // 远程服务器配置信息
  const config = require('./config');
  const { fileName } = config
  //清空服务器目标文件
  const removeFile = () => {
    fs.unlink(path, (err) => {
      if (err) {
        errorLog('删除失败~');
        return;
      }
      successLog('本地dist.zip文件已经删除成功！！')
    });

  }

  const connect = () => {
    //连接ssh服务器
    defaultLog(`尝试连接服务： ${config.host}`);
    try {
      let spinner = ora("正在连接ssh服务器");
      spinner.start();
      ssh.connect({
        host: config.host,
        username: config.username,
        password: config.password,
        port: config.port,
      }).then(() => {
        spinner.stop();
        successLog('SSH服务器 连接成功！');
        pushFile()
      })
        .catch((err) => {
          errorLog('SSH conneting fail:', err);
          process.exit(0);
        });
    } catch (error) {
      errorLog('SSH conneting fail:', error);
      process.exit(0);
    }
  }

  // 上传dist文件
  const pushFile = async () => {
    let spinner = ora("准备上传文件").start();
    let { Command } = config
    try {
      await runBeforeCommand(Command)
      await ssh.putFile(path, `${config.PATH}/${fileName}.zip`)
      successLog('The zip file is upload successful');
      spinner.text = "完成上传, 开始解压";
      // const command = `powershell -command "Expand-Archive -Path 'dist.zip' -DestinationPath './'"`;
      // && del ${ fileName }.zip
      // await runCommond(`cd C:/Users/Administrator/Desktop/nginx-1.6.3/seed&&${command}`); 
      await runCommond(`${Command.cd}&&${Command.unzip}`)
      
      // await runCommond(`${Command.cd}&&${Command.del} ${fileName}.zip`)
      spinner.stop();
      successLog('部署成功！');
      removeFile()
     
    } catch (error) {
      errorLog('文件上传失败:', error);
      process.exit(0);
    }

  }
  // ********* 执行清空线上文件夹指令 *********
  const runBeforeCommand = async (Command) => {
    let COMMONDS = Command.del
    defaultLog("清空目标文件");
    for (let i = 0; i < COMMONDS.length; i++) {
      await runCommond(`${Command.cd}&&${COMMONDS[i]}`);
    }
  };

  const runCommond = async (commond) => {
    ssh.execCommand(commond, {
      // cwd: 'C:/Users/Administrator/Desktop'
    })
      .then((result) => {
        successLog(`The update message is: ${result.stdout}`);

  
        // if (!result.stderr) {
        //   successLog('Gratefule! update success!');
        //   process.exit(0);
        // } else {
        //   errorLog('Something wrong:', result);
        //   process.exit(0);
        // }
      });
  }
  connect()

}
